import axios, { AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { message } from 'antd';

// 创建axios实例并配置基础URL
const api = axios.create({
  baseURL: 'http://127.0.0.1:9090',
  timeout: 5000
});

// 请求拦截器：添加JWT到请求头
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers = config.headers || {}; // 初始化headers避免undefined
    const token = localStorage.getItem('token');
    console.log('请求拦截器获取到的token:', token); // 调试日志
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError<{ message: string }>) => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理通用错误
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error: AxiosError) => {
    if (error.response) {
      const { status, data } = error.response;
        const { config } = error; // 提取请求配置对象
      if (status === 401) {
        // 区分登录接口的401和token过期场景
        if (config!.url === '/login') {
          message.error('用户名或密码错误');
        } else {
          // 处理token过期逻辑
          // localStorage.removeItem('token');
          // window.location.href = '/login';
        }
      }
      console.error(`请求错误：${status} ${(data as { message: string }).message}`);
    }
    return Promise.reject(error);
  }
);

export default api;